package com.apa7.keepaccounts.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;

@Component
public class Tool {

    private static HttpServletRequest request;

    @Autowired(required=true)
    public void setHttpServletRequest(HttpServletRequest request){
        Tool.request =request;
    }

    public static String getBodyParem(){
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        String returnData="";
        try{
            br = request.getReader();
            String str;
            while ((str = br.readLine()) != null)
            {
                sb.append(str);
            }
            br.close();
            returnData=sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            returnData=null;
        } finally {
            if (null != br)
            {
                try
                {
                    br.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        return returnData;
    }

    public static JSONObject getJsonOject(){
        String jsonData=getBodyParem();
        return JSON.parseObject(jsonData);
    }

    public static <T> List getJsonList( Class T){
        String jsonData=getBodyParem();
        return JSON.parseArray(jsonData,T);
    }

    public static <T>T getJsonT(Class<T> T){
        String jsonData=getBodyParem();
        System.out.println(jsonData);
        return JSON.parseObject(jsonData,T);
    }

    public static String getExceptionAllinformation_01(Exception ex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = new PrintStream(out);
        ex.printStackTrace(pout);
        String ret = new String(out.toByteArray());
        pout.close();
        try {
            out.close();
        } catch (Exception e) {
        }
        return ret;
    }
}
